package com.wenruo.funycollecte.fragment;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnLastItemVisibleListener;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.wenruo.funycollecte.R;
import com.wenruo.funycollecte.util.Client;
import com.wenruo.funycollecte.util.Item;
import com.wenruo.funycollecte.util.ResponseEntity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class ContentFragment extends Fragment {
	
	
	private LayoutInflater layoutInflater;
    private PullToRefreshListView mPullRefreshListView;
    private SimpleAdapter simpleAdapter;
    private LinkedList<Map<String, Object>> data;
    
    private Bundle args;
    private long maxCursor;
    private long currentCursor;

    @Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		args = getArguments();
		data = new LinkedList<Map<String, Object>>();
		fetchUpate();
		Log.i("fragment lifecycle", "fragment onCreate " + args.getString("category") + " " + args.getString("type"));
	}
    
	@Override
	public void onResume() {
		super.onResume();
		Log.i("fragment lifecycle", "fragment onResume " + args.getString("category") + " " + args.getString("type"));
	}
	
	@Override
	public void onPause() {
		super.onPause();
		Log.i("fragment lifecycle", "fragment onPause " + args.getString("category") + " " + args.getString("type"));
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.i("fragment lifecycle", "fragment onDestroy " + args.getString("category") + " " + args.getString("type"));
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		Log.i("fragment lifecycle", "fragment onActivityCreated " + args.getString("category") + " " + args.getString("type"));
	}
	
	@Override
	public void onDestroyView() {
		super.onDestroyView();
		Log.i("fragment lifecycle", "fragment onDestroyView " + args.getString("category") + " " + args.getString("type"));
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		layoutInflater = inflater;
		View contentView = layoutInflater.inflate(R.layout.fragment_content, container, false);
		mPullRefreshListView = (PullToRefreshListView) contentView.findViewById(R.id.pull_refresh_list);
		mPullRefreshListView.setMode(Mode.BOTH);
		mPullRefreshListView.getLoadingLayoutProxy(false, true).setPullLabel(getString(R.string.pull_to_load));
		mPullRefreshListView.getLoadingLayoutProxy(false, true).setRefreshingLabel(getString(R.string.loading));
		mPullRefreshListView.getLoadingLayoutProxy(false, true).setReleaseLabel(getString(R.string.release_to_load));
		
		mPullRefreshListView.setOnRefreshListener(new OnRefreshListener2<ListView>() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				fetchUpate();
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
				loadData();
			}
			
		});
		
		
		mPullRefreshListView.setOnLastItemVisibleListener(new OnLastItemVisibleListener() {

			@Override
			public void onLastItemVisible() {
				
			}
			
		});
		
		String[] from = {"itemContent", "itemFrom"};
        int[] to = {R.id.item_content, R.id.item_from};
		
		simpleAdapter = new SimpleAdapter(getActivity(), data, R.layout.list_view_content, from, to) {

			@Override
			public View getView(int position, View convertView, ViewGroup parent) {
				ViewHolder holder;
				 if (convertView == null) {
					 convertView = super.getView(position, convertView, parent);
					 holder = new ViewHolder();
					 holder.itemContent = (TextView) convertView.findViewById(R.id.item_content);
					 holder.itemFrom = (TextView) convertView.findViewById(R.id.item_from);
					 convertView.setTag(holder);
				} else {
					holder = (ViewHolder) convertView.getTag();
				}
				holder.itemContent.setText(data.get(position).get("itemContent").toString());
				holder.itemFrom.setText(data.get(position).get("itemFrom").toString());
				return convertView;
			}
			
		};
		mPullRefreshListView.setAdapter(simpleAdapter);
		
		Log.i("fragment lifecycle", "fragment onCreateView " + args.getString("category") + " " + args.getString("type"));
		
		return contentView;
	}
    
    static class ViewHolder {
    	TextView itemContent;
    	TextView itemFrom;
    }
    
    public void fetchUpate() {
    	
    	Map<String, String> params = new HashMap<>();
		params.put("category", args.getString("category"));
		params.put("type", args.getString("type"));
		params.put("maxCursor", Long.toString(maxCursor));
		params.put("size", "10");
		
		Client.fetchUpdate(params, new Listener<ResponseEntity>() {

			@Override
			public void onResponse(ResponseEntity responseEntity) {
				List<Item> itemList = responseEntity.getItems();
				if (itemList.size() > 0) {
					data.clear();
					for (Item item : itemList) {
						Map<String, Object> listViewItem = new HashMap<String, Object>();
						listViewItem.put("itemContent", item.getContent());
						listViewItem.put("itemFrom", item.getFromSiteName());
						listViewItem.put("id", item.getId());
						data.addFirst(listViewItem);
					}
					maxCursor = (long) data.getFirst().get("id");
					currentCursor = (long) data.getLast().get("id");
					simpleAdapter.notifyDataSetChanged();
					Toast.makeText(getActivity(), responseEntity.getMessage(), Toast.LENGTH_LONG).show();
				} else {
					Toast.makeText(getActivity(), "暂无更新", Toast.LENGTH_LONG).show();
				}
				mPullRefreshListView.onRefreshComplete();
			}
			
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("Get Item", "error", error);
			}
		});

    }
    
    public void loadData() {
    	
    	Map<String, String> params = new HashMap<>();
    	params.put("category", args.getString("category"));
		params.put("type", args.getString("type"));
		params.put("currentCursor", Long.toString(currentCursor));
		params.put("size", "10");
		
		Client.listItem(params, new Listener<ResponseEntity>() {

			@Override
			public void onResponse(ResponseEntity responseEntity) {
				List<Item> itemList = responseEntity.getItems();
				if (itemList.size() > 0) {
					for (Item item : itemList) {
						Map<String, Object> listViewItem = new HashMap<String, Object>();
						listViewItem.put("itemContent", item.getContent());
						listViewItem.put("itemFrom", item.getFromSiteName());
						listViewItem.put("id", item.getId());
						data.addLast(listViewItem);
					}
					currentCursor = (long) data.getLast().get("id");
					simpleAdapter.notifyDataSetChanged();
				}
				mPullRefreshListView.onRefreshComplete();
				Toast.makeText(getActivity(), responseEntity.getMessage(), Toast.LENGTH_LONG).show();
			}
			
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("Get Item", "error", error);
			}
			
		});
    }
}
